package org.piggy.test.http.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class FileSaveHandler {

    @Value("${piggy.config.localVirtualFilePath}")
    private String localVirtualFilePath;
    private final Logger logger = LoggerFactory.getLogger(FileSaveHandler.class);

    public String uploadFile(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        if(originalFilename!=null){
            int index = originalFilename.lastIndexOf(".");
            String fileType = originalFilename.substring(index);
            String fileName = uuid + fileType;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String datePath = sdf.format(new Date());
            String[] split = datePath.split("-");
            StringBuilder path = new StringBuilder();
            for(String s: split){
                path.append(s).append("/");
            }
            String url = localVirtualFilePath + path + fileName;
            File dir = new File(url);
            if (!dir.exists()) {
                boolean b = dir.mkdirs();
                logger.info(url+ " mkdir --> {}",b);
            }
            file.transferTo(dir);
            return url;
        }
        return null;
    }
}
